﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Achievement.BLL.Provider;
using Achievement.DataModels;
using Achievement.Web.Common;

namespace Achievement.Web.Controllers
{
    //[AuthorizeFilter(ValidataRole = 1)]
    [Authorize]
    public class FolderController : Controller
    {
        //
        // GET: /Folder/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult list()
        {
            var myFolders = FolderProvider.Instance.GetFidsByUid(UserInfo.CurrentUser.ID);
            List<VFolder> mylist = FolderProvider.Instance.GetVFolderTreeByIds(myFolders);
            List<JqGridModel> folders = new List<JqGridModel>();
            GetList(0, null, mylist, ref folders);
            var json = new
            {
                total = 1000,
                page = 1,
                records = 1000,
                rows = folders
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public void GetList( int level, VFolder folder,List<VFolder> list, ref List<JqGridModel> folders)
        {
            List<VFolder> query = null;
            List<long?> ids = list.Select(f => (long?)f.ID).ToList();
            if (folder == null)
            {
                query = list.Where(l => !ids.Contains(l.Parent)).ToList();
            }
            else
            {
                query = list.Where(l => l.Parent == folder.ID).ToList();
            }
            foreach (var item in query)
            {
                JqGridModel jqg = new JqGridModel();
                jqg.id = item.ID;

                if (item.SunCount > 0)
                {
                    jqg.cell = new[] { item.Name, item.SunCount.ToString(), 
                    (UserInfo.ValidataRole(1)?"<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/editfolder?id=0&folder=" + item.ID + "'})\">创建子文件夹</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/editfolder?id=" + item.ID + "'})\">修改</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/setuserfolder?fid=" + item.ID + "'})\">设置用户</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"deletefolder(" + item.ID + ")\">删除</a>":"")
                    , level.ToString(), item.Parent == null ? null : item.Parent.ToString(), "false", "false" };
                    folders.Add(jqg);
                    GetList(level + 1, item, list, ref folders);
                }
                else
                {
                    jqg.cell = new[] { item.Name, item.SunCount.ToString(), 
                    (UserInfo.ValidataRole(1)?"<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/editfolder?id=0&folder=" + item.ID + "'})\">创建子文件夹</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/editfolder?id=" + item.ID + "'})\">修改</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/folder/setuserfolder?fid=" + item.ID + "&"+new Random().Next(9999)+"'})\">设置用户</a>" +
                    "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"deletefolder(" + item.ID + ")\">删除</a>":"")
                    , level.ToString(), item.Parent == null ? null : item.Parent.ToString(), "true", "false" };
                    folders.Add(jqg);
                }
            }
        }

        public void GeDropDownList(int level, VFolder folder, List<VFolder> list, ref string str)
        {
            List<VFolder> query = null;
            List<long?> ids = list.Select(f => (long?)f.ID).ToList();
            if (folder == null)
            {
                query = list.Where(l => !ids.Contains(l.Parent)).ToList();
            }
            else
            {
                query = list.Where(l => l.Parent == folder.ID).ToList();
            }
            foreach (var item in query)
            {
                if (item.SunCount > 0)
                {

                    str += string.Format("<li rel=\"{0}\">{1}\r\n<ul>\r\n", item.ID, item.Name);
                    GeDropDownList(level + 1, item, list, ref str);
                    str += "</ul>\r\n</li>\r\n";
                }
                else
                {
                    str += string.Format("<li rel=\"{0}\">{1}</li>\r\n", item.ID, item.Name);
                }
                
            }
        }

        [HttpGet]
        public ActionResult EditFolder(long id, long? folder)
        {
            VFolder f = null;
            var myFolders = FolderProvider.Instance.GetFidsByUid(UserInfo.CurrentUser.ID);
            List<VFolder> mylist = FolderProvider.Instance.GetVFolderTreeByIds(myFolders);
            if (id > 0)
            {
                f = mylist.Where(foler => foler.ID == id).FirstOrDefault() ?? new VFolder();
            }
            else
            {
                f = new VFolder();
                f.Parent = folder;
                f.Name = string.Empty;
                f.ID = 0;
            }
            string str = string.Empty;
            GeDropDownList(0, null, mylist, ref str);
            if (myFolders.Contains(0))
            {
                str = string.Format("<li rel=\"{0}\">{1}\r\n<li>\r\n", 0, "成果库") + str;
            }
            ViewData["ddlParent"] = str;
            return View(f);
        }

        [HttpPost]
        public ActionResult SaveFolder(long id, long folder, string name)
        {
            Folder f = new Folder();
            if (id > 0)
            {
                f = FolderProvider.Instance.GetFolderById(id);
            }
            f.Name = name;
            if (folder > 0)
                f.Parent = folder;
            else
                f.Parent = null;
            FolderProvider.Instance.SaveFolder(f);
            return Redirect("/Folder");
        }

        
        public ActionResult DeleteFolder(long id)
        {
            FolderProvider.Instance.DeleteFolderById(id);
            return Redirect("/Folder");
        }

        public ActionResult SetUserFolder(long fid)
        {
            List<Users> users = UsersProvider.Instance.GetUserList();
            List<long> fUsers = FolderProvider.Instance.GetFolderUsersByFId(fid).Select(fu=>fu.UID).ToList();
            List<SelectListItem> fList = new List<SelectListItem>();
            List<SelectListItem> ulist = new List<SelectListItem>();
            if (fList != null)
            {
                fList = (from u in users where !fUsers.Contains(u.ID) select (new SelectListItem() { Text = u.Name, Value = u.ID.ToString() })).ToList();
            }
            if (ulist != null)
            {
                ulist = (from u in users where fUsers.Contains(u.ID) select (new SelectListItem() { Text = u.Name, Value = u.ID.ToString() })).ToList();
            }
            ViewData["lbFUsers"] = fList;
            ViewData["lbUsers"] = ulist;
            return View();
        }

        public ActionResult SaveFolderUser(string hdnAdd, string hdnDelete,long fid)
        {
            FolderProvider.Instance.AddFolderUser(hdnAdd.Split(','),fid);
            FolderProvider.Instance.DeleteFolderUser(hdnDelete.Split(','), fid);
            return Redirect("/folder");
        }
    }

    public class JqGridModel
    {
        public long id
        {
            get;
            set;
        }
        public string[] cell
        {
            get;
            set;
        }
    }
}
